package com.wr.modules.system.controller;


import com.wr.api.system.domain.LoginUser;
import com.wr.common.core.result.R;
import com.wr.common.core.utils.StringUtils;
import com.wr.api.system.domain.SysUserBo;
import com.wr.api.system.domain.SysUserWxBo;
import com.wr.modules.system.service.ISysPermissionService;
import com.wr.modules.system.service.ISysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author MyPC
 */
@Tag(name = "A - 认证授权接口")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysPermissionService iSysPermissionService;


    @GetMapping("/infoByUk/{uk}")
    public R<LoginUser> infoByUk(@PathVariable("uk") String uk) {
        SysUserBo sysUserBo = iSysUserService.findUserByUk(uk);
        if (StringUtils.isNull(sysUserBo)) {
            return R.fail("未查到账号信息！");
        }
        return R.ok(getLoginUser(sysUserBo));
    }

    @GetMapping("/infoByMobile")
    @Operation(summary = "根据手机号获取用户信息")
    public R<LoginUser> infoByMobile(@RequestParam("mobile") String mobile, @RequestParam("isCreate") Boolean isCreate) {
        SysUserBo sysUserBo = iSysUserService.findUserByMobile(mobile, isCreate);
        return R.ok(getLoginUser(sysUserBo));
    }

    @GetMapping("/infoByMailbox")
    @Operation(summary = "根据邮箱获取用户信息")
    public R<LoginUser> infoByMailbox(@RequestParam("mailbox") String mailbox, @RequestParam("isCreate") Boolean isCreate) {
        SysUserBo sysUserBo = iSysUserService.findUserByMailbox(mailbox, isCreate);
        return R.ok(getLoginUser(sysUserBo));
    }

    @PostMapping("/infoByWx")
    @Operation(summary = "根据微信获取用户信息")
    public R<LoginUser> infoByWx(@RequestBody SysUserWxBo sysUserWxBo) {
        SysUserBo sysUserBo = iSysUserService.findUserByWx(sysUserWxBo);
        return R.ok(getLoginUser(sysUserBo));
    }

    @Operation(summary = "根据手机号获取用户信息")
    @GetMapping("/register")
    public R<Boolean> registerUserInfo(@RequestParam("uk") String uk, @RequestParam("pk") String pk) {
        iSysUserService.registerUser(uk, pk);
        return R.ok(true);
    }

    /**
     * 获取用户信息
     *
     * @param sysUserBo
     * @return
     */
    private LoginUser getLoginUser(SysUserBo sysUserBo) {
        // 角色集合
        Set<String> roles = iSysPermissionService.getRolePermission(sysUserBo);
        // 权限集合
        Set<String> permissions = iSysPermissionService.getMenuPermission(sysUserBo);
        LoginUser loginUser = new LoginUser();
        loginUser.setSysUserBo(sysUserBo);
        loginUser.setRoles(roles);
        loginUser.setPermissions(permissions);
        return loginUser;
    }
}
